import Toast from '../../../vant/toast/toast';
import { submitShareOrder, getFruitDetail } from '../../../utils/api/index.js';
import md5 from '../../../utils/md5.js';
const app = getApp();
Page({
  data: {
    farmerToken: '',
    shareToken: '',
    farmerName: '',
    fruitName: '',
    farmerPhone: '',
    recipientName: '',
    phoneNumber: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    addressParseStr: '',
    largeBox: 0,
    smallBox: 0,
    region: [],
    navHeight: app.globalData.statusHeight,
    access_token: '',
    discernFlag: true,
    showPicker: false,
    companyId: undefined,
    fruitOrderArr: [] // 规格排序
  },

  onLoad(query) {
    console.log(query, 'query');
    if (query.shareToken) {
      this.setData({
        farmerToken: query.farmerToken,
        shareToken: query.shareToken,
        fruitName: query.fruitName,
        farmerName: query.farmerName,
        farmerPhone: query.farmerPhone,
        fruitId: query.fruitId,
        companyId: query.companyId
      });
    }
    this.getToken();
    this.getData();
  },
  getData() {
    getFruitDetail(this.data.fruitId).then(res => {
      if (res.resultStatus) {
        const attributes = res.resultData[0].attributes;
        const fruitOrderArr = attributes.map(item => {
          const attributeCombination = JSON.parse(item.attributeCombination);
          const temp = {
            attributeId: item.attributeId,
            quantity: 0,
            attributeValue: attributeCombination
              .map(item => {
                return item.attributeValue;
              })
              .join('')
          };
          return temp;
        });
        this.setData({
          fruitOrderArr
        });
      }
    });
  },

  // 获取access_token
  getToken() {
    wx.request({
      url:
        'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=W0g3zCfydNC3tWtG0Y1wWFoF&client_secret=QFfqrGr9HzDcKV6gQQYuP9RMmyWCC4R8',
      method: 'POST',
      data: {},
      success: ({ data }) => {
        const access_token = data.access_token;
        if (access_token) {
          this.setData({
            access_token: access_token
          });
        }
        console.log(data);
      },
      fail: err => {
        console.log(err);
      }
    });
  },

  toHome() {
    wx.switchTab({
      // url: '/pages/order/index/index',
      url: '/pages/order/downOrder/downOrder'
    });
  },

  numberChange(e) {
    let num = isNaN(Number(e.detail.value)) ? 0 : Number(e.detail.value);
    const index = e.target.dataset.index;
    const fruitOrderArr = this.data.fruitOrderArr;
    if (fruitOrderArr[index].quantity > 0) {
      fruitOrderArr[index].quantity = num;
      this.setData({
        fruitOrderArr
      });
    }
  },

  bindRegionChange(e) {
    const value = e.detail.value;
    const province = value[0];
    const city = value[1];
    const district = value[2];
    this.setData({
      province,
      city,
      district,
      region: [province, city, district]
    });
  },

  inputChange(value) {
    const type = value.target.dataset.type;
    this.setData({
      [type]: value.detail.value
    });
  },

  clearAddressParse() {
    this.setData({
      addressParseStr: ''
    });
  },

  // 识别
  addressParse() {
    if (this.data.addressParseStr.trim()) {
      this.handleAddressRecognition(this.data.addressParseStr);
    }
  },
  handleAddressRecognition(val) {
    if (this.data.access_token) {
      if (this.data.discernFlag) {
        this.setData({
          discernFlag: false,
        });
        setTimeout(() => {
          this.setData({
            discernFlag: true,
          });
        }, 1000);
        let obj = {
          method: 'cloud.address.resolve',
          app_id: 107200,
          ts: Date.now(),
          api_key: '3beda353ef4d02ec0387e279cd06194407cb9b67',
        };
        wx.request({
          url: 'https://kop.kuaidihelp.com/api',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          },
          data: {
            method: obj.method,
            app_id: obj.app_id,
            ts: obj.ts,
            sign: md5(obj.app_id + obj.method + obj.ts + obj.api_key),
            data: JSON.stringify({
              text: val,
              multimode: false,
              resolveTown: true,
            }),
          },
          success: ({ data }) => {
            console.log(data);
            if (!data.code) {
              let result = data.data[0];
              console.log(result);
              this.setRecipient(result);
            } else {
              wx.showToast({
                title: data.msg,
                icon: 'none',
                mask: true,
              });
            }
          },
        });
      }
    } else {
      wx.showToast({
        title: '识别失败',
        icon: 'none'
      });
    }
  },
  reduceBox(e) {
    const index = e.currentTarget.dataset.index;
    const fruitOrderArr = this.data.fruitOrderArr;
    if (fruitOrderArr[index].quantity > 0) {
      fruitOrderArr[index].quantity = fruitOrderArr[index].quantity - 1;
      this.setData({
        fruitOrderArr
      });
    }
  },

  addBox(e) {
    console.log(e);
    const index = e.currentTarget.dataset.index;
    const fruitOrderArr = this.data.fruitOrderArr;
    console.log(fruitOrderArr, 'fruitOrderArr');
    fruitOrderArr[index].quantity = fruitOrderArr[index].quantity + 1;
    this.setData({
      fruitOrderArr
    });
  },
  submitData() {
    const loginInfo = wx.getStorageSync('loginInfo');
    if (!loginInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          wx.navigateTo({
            url: '/pages/mine/login/index'
          });
        }
      });
    } else if (!this.data.recipientName) {
      wx.showToast({
        title: '请输入收件人姓名',
        icon: 'none'
      });
    } else if (!this.data.phoneNumber) {
      wx.showToast({
        title: '请输入电话号码',
        icon: 'none'
      });
    } else if (this.data.phoneNumber.length !== 11) {
      wx.showToast({
        title: '电话号码长度为11位',
        icon: 'none'
      });
    } else if (!this.data.province || !this.data.city || !this.data.district) {
      wx.showToast({
        title: '请输入所在地区',
        icon: 'none'
      });
    } else if (!this.data.detailAddress) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
    } else if (this.checkSpecification()) {
      wx.showToast({
        title: '请选择规格数量',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '加载中...',
        icon: 'loading'
      });
      // 处理水果属性
      const fruit = {
        fruitId: this.data.fruitId,
        attributes: this.data.fruitOrderArr.filter(item => {
          if (item.quantity > 0) {
            return {
              attributeId: item.attributeId,
              quantity: item.quantity
            };
          }
        })
      };
      const obj = {
        farmerToken: this.data.farmerToken,
        shareToken: this.data.shareToken,
        province: this.data.province,
        city: this.data.city,
        district: this.data.district,
        detailAddress: this.data.detailAddress,
        recipientName: this.data.recipientName,
        phoneNumber: this.data.phoneNumber,
        companyId: this.data.companyId,
        fruit
      };
      console.log(obj)
      submitShareOrder(obj).then(res => {
        if (res.resultStatus) {
          wx.showToast({
            mask: true,
            title: '提交成功',
            icon: 'success'
          });
          this.setData({
            recipientName: '',
            phoneNumber: '',
            province: '',
            city: '',
            district: '',
            detailAddress: '',
            largeBox: 0,
            smallBox: 0,
            region: [],
            addressParseStr: '',
            fruitOrderArr: []
          });
          this.getData();
        } else {
          wx.showToast({
            title: res.errorMessage,
            icon: 'none'
          });
        }
      });
    }
  },
  // 验证规格
  checkSpecification() {
    const fruitOrderArr = this.data.fruitOrderArr;
    const flag = fruitOrderArr.every(item => {
      return item.quantity == 0;
    });
    return flag;
  },
  // 地址选中
  handleChoosed(e) {
    const chooseData = e.detail;
    const value = chooseData.map(item => {
      return item.label;
    });
    this.setData({
      province: value[0],
      city: value[1],
      district: value[2],
      region: [value[0], value[1], value[2]]
    });
  },
  handleClosePicker() {
    this.setData({
      showPicker: false
    });
  },
  openPicker() {
    // this.setData({
    //   show: true
    // })
    this.setData({
      showPicker: true
    });
  },
  // 设置收件人信息
  setRecipient(result){
    console.log(result)
    const obj = {
      province: result.province_name,
      city: result.city_name,
      district: result.county_name,
      detailAddress:
        (result.town_name ? result.town_name.trim() : '') +
        (result.detail ? result.detail.trim() : ''),
      recipientName: result.name,
      phoneNumber: result.mobile,
      region: [],
    };
    if (
      result.province_name &&
      result.city_name &&
      result.county_name
    ) {
      obj.region = [
        result.province_name,
        result.city_name,
        result.county_name,
      ];
    }
    //   二次过滤   空数据不覆盖
    let newObj = {};
    for (let key in obj) {
      if (obj[key].length) {
        newObj[key] = obj[key];
      }
    }
    this.setData(newObj);
  }
});
